import {
  isIos,
  isEcommunityApp,
  isBrandApp,
  isWuXiaoBoApp,
  isSDK,
  isELearnApp,
} from "../../utils/checkEnv";
import {
  //实物商品
  ENTITY_GOODS,
  //课时包
  OFFLINE_PERIOD,
  //服务类商品
  SERVICE_GOODS,
  //活动管理
  ACTIVITY_MANAGE,
  //线下课
  OFFLINE_CLASS,
  //直播
  LIVE,
  //小班课
  BAN_TAK,
  //大班课
  LARGE_CLASS,
} from "../../constants/constant";

import { PayWayEnum, isVirtualPayWay } from "./pay-way";

//品牌app
function resolvePayWaysOnBrandApp(payWays, spuType) {
  const isMatch = [
    ENTITY_GOODS,
    OFFLINE_PERIOD,
    SERVICE_GOODS,
    ACTIVITY_MANAGE,
    OFFLINE_CLASS,
    LIVE,
    BAN_TAK,
    LARGE_CLASS,
  ].includes(spuType);

  if (isIos) {
    if (isMatch) {
      return payWays;
    } else {
      return payWays.filter((item) => isVirtualPayWay(item.pay_way));
    }
  }

  return payWays.filter((item) => !isVirtualPayWay(item.pay_way));
}

//吴晓波app
function resolvePayWaysOnWuXiaoBoApp(payWays, spuType) {
  const isMatch = [
    ENTITY_GOODS,
    OFFLINE_PERIOD,
    SERVICE_GOODS,
    ACTIVITY_MANAGE,
    OFFLINE_CLASS,
    ALIVE,
    BAN_TAK,
    LARGE_CLASS,
  ].includes(spuType);
  if (isIos && !isMatch) {
    return payWays.filter((item) => isVirtualPayWay(item.pay_way));
  }
  return payWays;
}

//圈子app
function resolvePayWaysOnEcommunityApp(payWays) {
  if (isIos) {
    return payWays.filter((item) => isVirtualPayWay(item.pay_way));
  }
  return payWays.filter((item) => !isVirtualPayWay(item.pay_way));
}

//小鹅通app
function resolvePayWaysOnEleranApp(payWays) {
  if (isIos) {
    return payWays.filter((item) => isVirtualPayWay(item.pay_way));
  }
  return payWays;
}

function formatPayWays(payWayInfo) {
  const { ways, huaBeiInstallment, orderPrice } = payWayInfo;
  if (huaBeiInstallment) {
    const huabeiPayWay = ways?.find(
      (item) => item.pay_way === PayWayEnum.PayWayAliPayHB
    );
    if (huabeiPayWay) {
      huabeiPayWay.hua_bei_installment_select = huaBeiInstallment;
    }
  }

  const formatedPayWays = ways || [];

  formatedPayWays.forEach((item) => {
    const { pay_way, virtual_coin_balance } = item;
    if (isVirtualPayWay(pay_way)) {
      item.isInsufficientBalance = virtual_coin_balance < orderPrice;
      item.balance = virtual_coin_balance;
      item.showLimitTips = formatedPayWays.length < 2;
    }
  });

  return formatedPayWays;
}

//确定可以在APP内嵌场景中显示的支付方式
export default function resolvePayWaysOnApp(payWayInfo, resourceType) {
  const formatedPayWays = formatPayWays(payWayInfo);
  if (isWuXiaoBoApp) {
    return resolvePayWaysOnWuXiaoBoApp(formatedPayWays, resourceType);
  } else if (isBrandApp) {
    return resolvePayWaysOnBrandApp(formatedPayWays, resourceType);
  } else if (isEcommunityApp) {
    return resolvePayWaysOnEcommunityApp(formatedPayWays);
  } else if (isELearnApp) {
    return resolvePayWaysOnEleranApp(formatedPayWays);
  } else {
    return formatedPayWays;
  }
}
